<?php

namespace App\Http\Middleware;

use App\Utils\Token;
use Closure;
use Illuminate\Http\Request;

class VerifyJwtToken
{

    private $white_list = [
        '/',
        'login/loginIn',
        'login/register',
        'im/getImHistoryList',
    ];

    private $white_prefix = [
        'test/'
    ];

    /**
     * 白名单验证方法
     * @param string $path_info 路径 login/loginIn
     * @return bool 是白名单则返回true 否则返回false
     */
    private function white_verify(string $path_info): bool
    {
        //验证白名单方法
        if (in_array($path_info, $this->white_list)) {
            return true;
        }
        //以开头的
        foreach ($this->white_prefix as $wp) {
            if (strpos($path_info, $wp) === 0) {
                return true;
            }
        }
        //否则返回false
        return false;
    }

    public function handle(Request $request, Closure $next)
    {
        # 开头白名单验证
        //验证jwtToken 并且通过白名单
        if (!$this->white_verify($request->path())) {
            # 不是白名单则需要验证token
            $token_str = $request->header('Authorization');
            $token_str = $token_str ?: '';
            $jwtToken = new Token();
            $res = $jwtToken->verifyToken($token_str);
            # 验证失败不给值
            if ($res['code'] === 500) {
                return response()->json(['code' => 401, 'message' => '未授权']);
            } else {
                # 验证成功将用户id传给所有的请求中(方便调用)
                $request->merge(
                    ['token_uid' => $res['data']['uid']]
                );
            }
        }

        return $next($request);
    }
}
